import fetch from 'node-fetch';
import fs from 'fs';
import { Config } from '../app';
import { bootEvent } from '../boot';
import { makeLabelLogger } from './logger';
import { DataCenterUrl, publishMessage, syncRedisCommon } from '../syncserver/smain';
import express = require('express');
import { sexTimeout } from './tools';
import { SyncAdImageMessageType, SyncConfigMessageType, SyncUserMessageType } from '../service/api/sync';

let { llog, lerror } = makeLabelLogger('mbsync-pull');

let ignorePubWhenSame = true;
// ignorePubWhenSame=false;

bootEvent.on('appInit', async (app: express.Application) => {
	llog('init');
	app.use('/pullChangedUsers', pullChangedUsers);
	app.use('/pullDataConfig', pullDataConfig);

	sexTimeout({ dt: 1000 * 30, atonce: true, handler: pullChangedUsers });
	sexTimeout({ dt: 1000 * 30, atonce: true, handler: pullDataConfig });
	sexTimeout({ dt: 1000 * 30, atonce: true, handler: pullAdImage });
});

let pullChangedUsers = async function() {
	try {
		let tmKey = 'config:lastPullUserTime';
		let lastPullUserTime = await syncRedisCommon.get(tmKey);
		// lastPullUserTime = '1000000';

		let url = `${DataCenterUrl}/account-lastupdate`;
		llog('pullChangedUsers', url, lastPullUserTime);
		let nextTime = Date.now();
		let res = await fetch(url, {
			method: 'post',
			body: JSON.stringify({
				times: lastPullUserTime,
			}),
			timeout: 1000 * 25,
		});
		let text = await res.text();
		// llog('pullChangedUsers1', text);
		let data = JSON.parse(text);
		llog('pullChangedUsers2', data.result.length);
		if (data.result.length > 0) {
			publishMessage(SyncUserMessageType, { type: 'UpdateUser', users: data.result });
		}
		syncRedisCommon.set(tmKey, nextTime.toString());
	} catch (e) {
		llog('pullChangedUsers fail', e.message);
	}
};

let pullDataConfig = async function() {
	let url = `${DataCenterUrl}/index-getcode`;
	let key = `config:dataConfig`;
	llog('pullDataConfig', url);
	try {
		let res = await fetch(url, { timeout: 1000 * 25 });
		let text = await res.text();
		let json = JSON.parse(text);

		let lastValue = await syncRedisCommon.get(key);
		if (text == lastValue && ignorePubWhenSame) {
			llog('pullDataConfig not change, skip');
			return;
		}
		await syncRedisCommon.set(key, text);

		json.recvTime = Date.now();
		publishMessage(SyncConfigMessageType, { data: JSON.stringify(json) });
	} catch (e) {
		llog('pulldataconfig fail', e.message);
	}
};

let pullAdImage = async function() {
	let url = `${DataCenterUrl}/image`;
	let key = `config:adImage`;
	let lpr = 'pullAdImage';
	llog(lpr, url);
	try {
		let res = await fetch(url, { timeout: 1000 * 25 });
		let text = await res.text();
		let json = JSON.parse(text);

		let lastValue = await syncRedisCommon.get(key);
		if (text == lastValue && ignorePubWhenSame) {
			llog(lpr, 'not change, skip');
			// return;
		}
		await syncRedisCommon.set(key, text);
		json.recvTime = Date.now();
		publishMessage(SyncAdImageMessageType, { data: JSON.stringify(json.result) });
	} catch (e) {
		llog(lpr, 'fail', e.message);
	}
};
